package com.lineage.server.timecontroller.npc;

import com.lineage.server.model.Instance.L1MonsterInstance;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.WorldMob;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class NpcHprTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(NpcHprTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  
  public void start() {
    int timeMillis = 1200;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 1200L, 1200L);
  }
  
  public void run() {
    try {
      Collection<L1MonsterInstance> allMob = WorldMob.get().all();
      if (allMob.isEmpty()) {
        _log.error("Npc HP自然回复时间轴异常重启 allMob.isEmpty()");
        return;
      } 
      Iterator<L1MonsterInstance> iter = allMob.iterator();
      while (iter.hasNext()) {
        L1MonsterInstance mob = iter.next();
        if (mob.isHpR())
          hpUpdate(mob); 
      } 
    } catch (Exception e) {
      _log.error("Npc HP自然回复时间轴异常重启", e);
      if (this._timer != null)
        GeneralThreadPool.get().cancel(this._timer, false); 
      NpcHprTimer npcHprTimer = new NpcHprTimer();
      npcHprTimer.start();
    } 
  }
  
  private static void hpUpdate(L1MonsterInstance mob) {
    int hprInterval = mob.getNpcTemplate().get_hprinterval();
    if (hprInterval <= 0)
      hprInterval = 10; 
    long nowtime = System.currentTimeMillis() / 1000L;
    long LastHprTime = mob.getLastHprTime();
    if (nowtime - LastHprTime >= hprInterval) {
      int hpr = mob.getNpcTemplate().get_hpr();
      if (hpr <= 0)
        hpr = 2; 
      hprInterval(mob, hpr);
      mob.setLastHprTime(nowtime);
    } 
  }
  
  private static void hprInterval(L1MonsterInstance mob, int hpr) {
    try {
      if (mob.isHpRegenerationX())
        mob.setCurrentHp(mob.getCurrentHp() + hpr); 
    } catch (Exception e) {
      _log.error("Npc 执行回复HP发生异常", e);
      mob.deleteMe();
    } 
  }
}
